package eu.inmite.harmony.lib.validations.form;

import eu.inmite.harmony.lib.validations.util.LogUtil;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;

/**
 * @author Tomas Vondracek
 */
public class Utils {
    private static DecimalFormat numberFormat = null;

    private Utils() {
    }

    private static DecimalFormat getBigDecimalFormatter() {
        if (numberFormat == null) {
            numberFormat = new DecimalFormat();
            numberFormat.setMinimumFractionDigits(2);
            numberFormat.setMaximumFractionDigits(2);
            numberFormat.setParseBigDecimal(true);
        }
        return numberFormat;
    }

    /**
     * parseAmountWithDecimalFormatter()
     *
     * @param text text
     * @return BigDecimal
     */
    public static BigDecimal parseAmountWithDecimalFormatter(String text) {
        if (isEmpty(text)) {
            return BigDecimal.ZERO;
        }

        BigDecimal amount = null;
        try {
            amount = (BigDecimal) getBigDecimalFormatter().parse(text);
        } catch (ParseException e) {
            LogUtil.warn("validation", "failed to parse amount with number formatter " + text);
        }
        return amount;
    }

    /**
     * parseAmount()
     *
     * @param text text
     * @return BigDecimal
     */
    public static BigDecimal parseAmount(String text) {
        if (isEmpty(text)) {
            return BigDecimal.ZERO;
        }
        BigDecimal amount = parseAmountWithDecimalFormatter(text);
        if (amount != null) {
            return amount;
        } else {
            // decimal formatter failed let's try it the simple way
            try {
                amount = new BigDecimal(text);
            } catch (Exception e) {
                LogUtil.error("validation", "failed to create BigDecimal from " + text);
            }
        }
        return amount;
    }

    /**
     * Returns true if the string is null or 0-length.
     *
     * @param str the string to be examined
     * @return true if str is null or zero length
     */
    public static boolean isEmpty(CharSequence str) {
        if (str == null || str.length() == 0) {
            return true;
        } else {
            return false;
        }
    }
}
